﻿/*************************************************************************************

- CLR版本：        4.0.30319.42000
- 类 名 称：       ToolMove
- 机器名称：       YTE
- 命名空间：       LD.Tool.BC
- 文 件 名：       ToolMove
- 创建时间：       2022/6/16 9:24:57
- 作    者：       YTE
- 说   明：
- 修改时间：
- 修 改 人：
  *************************************************************************************/

using LD.BC;
using LD.Host;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace LD.Tool
{
    [Tool(FrmParam = "ToolMoveFrm", Text = "点位移动", ToolType = ToolEnum.BC)]
    class ToolMove : BaseTool
    {
        public override OpResult Execute(TB_Tool model)
        {
            try
            {
                stopwatch.Start();
                if (model.Param != null)
                {
                    var toolMoveModel = Newtonsoft.Json.JsonConvert.DeserializeObject<Move>(model.Param);
                    if (toolMoveModel != null)
                    {
                        var point = Appbus.PartNo.Config.AxisPoint.Where(p => p.Name == toolMoveModel.Point).FirstOrDefault();
                        if (point != null)
                        {
                            Move(point, toolMoveModel);

                            isSuccess = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };
        }
        private void Move(TB_Point point, Move toolMoveModel)
        {
            Log4.Log.Info($"【{point.Name}】开始移动");
            bool isNeedMove = false;
            point.Move(toolMoveModel.WaitOver);

            //判断是否有光栅
            while (LightStopHelper.Instance.IsPause
                && Appbus.StateEnum == StateEnum.自动模式)
            {
                isNeedMove = true;
                Task.Delay(5).Wait();
            }
            if (BCAlertHelper.GetErrorQty)
                return;

            foreach (var item in point.AxisPointDic)
            {
                if (BcFactory.Instance.Control.GetAxisPosition(item.Value.AxisId) != item.Value.Point
                    && !BCAlertHelper.GetErrorQty)
                {
                    isNeedMove = true;
                    break;
                }
            }

            if (isNeedMove
                && !BCAlertHelper.GetErrorQty
                && Appbus.StateEnum == StateEnum.自动模式)
                Move(point, toolMoveModel);
        }
    }
}
